﻿namespace SLClient.ViewModels
{
    using SLClient;
    using SLClient.Extension;
    using SLClient.Infrastructure;
    using SLClient.ServiceAPI;
    using System;
    using System.Collections.ObjectModel;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Input;

    public class LowerOnlineViewModel : ViewModelBase
    {
        private Visibility _loadVisibilty = Visibility.Visible;
        public ObservableCollection<UserInfo> _onlineUsers = new ObservableCollection<UserInfo>();

        public LowerOnlineViewModel()
        {
            this.PageCollection = new PagedCollectionView(this._onlineUsers);
            this.Init();
            this.CommandInit();
        }

        public void CommandInit()
        {
            RelayCommand command = new RelayCommand(this.Refresh) {
                IsEnabled = true
            };
            this.RefreshCommand = command;
        }

        private void Init()
        {
            this.PageCollection.Refresh();
            ServiceClient instance = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            instance.GetOnlineAgentsCompleted += delegate (object obj, GetOnlineAgentsCompletedEventArgs arg) {
                if (arg.Error == null)
                {
                    this._onlineUsers.Clear();
                    foreach (UserInfo info in arg.Result)
                    {
                        this._onlineUsers.Add(info);
                    }
                    this.PageCollection = new PagedCollectionView(this._onlineUsers);
                }
                else
                {
                    App.Show("获取数据发生错误！");
                }
                this.LoadVisibilty = Visibility.Collapsed;
            };
            instance.GetOnlineAgentsAsync();
        }

        public void Refresh()
        {
            this.LoadVisibilty = Visibility.Visible;
            this.Init();
        }

        public Visibility LoadVisibilty
        {
            get
            {
                return this._loadVisibilty;
            }
            set
            {
                this._loadVisibilty = value;
                base.Notify<Visibility>(() => this.LoadVisibilty);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LowerOnlineViewModel)), (MethodInfo)(LowerOnlineViewModel.get_LoadVisibilty)), new ParameterExpression[0]));
            }
        }

        public PagedCollectionView PageCollection { get; set; }

        public ICommand RefreshCommand { get; set; }
    }
}

